<template>
	<view>
		<!-- pages/goodsDetail/index.wxml -->
		<!-- 头部 -->
		<navber id="head-navber" :navbarBg="navbarBg" :navbarData="navbarData"></navber>

		<view class="detail">
			<view class="detail-photo">
				<swiper :indicator-dots="true" indicator-color="rgba(0,0,0,0.5)"
					indicator-active-color="rgba(255,255,255,1.00)" :autoplay="true" class="detail-photo-swiper">
					<swiper-item v-for="(item, index) in goodsData.goods_photo" :key="item.key">
						<image mode="aspectFill" :src="item" class="detail-photo-swiper-img"></image>
					</swiper-item>
				</swiper>
			</view>
			<view class="detail-vip" v-if="goodsData.goods_special==0&&bean==''">
				<view class="detail-vip-left">
					<view class="detail-vip-left-text">返现</view>
					<view class="detail-vip-left-price">¥{{(goodsItem.goods_return_price)}}</view>
				</view>
				<view class="detail-vip-right">
					<view class="detail-vip-right-text">推广</view>
					<view class="detail-vip-right-price">¥{{goodsItem.goods_ratio_price}}</view>
				</view>
			</view>
			<view class="detail-title">
				{{goodsData.goods_title}}
			</view>
			<view class="detail-tip" v-if="goodsData.goods_tag.length > 0">
				<span class="tip-span" v-for="(item, index) in goodsData.goods_tag" :key="index">{{ item }}</span>
			</view>
			<!-- <view class="detail-price">
    		<view class="detail-price-layer">
    			<view class="detail-price-discount">¥{{goodsData.goods_min_price}}</view>
    			<view class="detail-price-primary">{{goodsData.goods_max_price}}</view>
    		</view>
    	</view> -->
			<view class="attr-goods-plan">
				<view class="attr-name">
					<view class="goods-price">
						<view class="sell_price">¥{{ goodsItem.goods_sell_price }}</view>
						<!-- <view class="price-discounts-bean" v-if="bean=='bean'">（{{parseInt(goodsItem.goods_sell_price)}}
							趣豆）</view> -->
						<view class="market_price">库存{{ goodsItem.goods_storage }}件</view>
					</view>
				</view>
				<view class="attr-name" v-if="bean=='gift'">
					<view class="goods-price">
						<view class="sell_price">礼包赠送：</view>
						<view class="price-discounts-bean">{{parseInt(goodsItem.bean)}}
							（趣豆)</view>
						<view class="market_price" v-if="goodsItem.coupon<=0">{{ goodsItem.coupon}}(商品兑换券)</view>
					</view>
				</view>
				<!-- <scroll-view scroll-y='true' class="attr-list">
          <view class="attr-item-spec" wx:for="{{attrList}}" wx:key="index">
            <view class="attr-iten-line"></view>
            <view class="attr-item-spec-name">{{item.name}}</view>
            <view class="attr-item-spec-list">
              <view wx:for="{{item.list}}" wx:for-index="indexx" wx:key="indexx" wx:for-item="itemx" class="attr-spec-item {{itemx.selected?'active':''}} {{itemx.disabled?'disabled':''}}" bindtap="onSelectAttr" data-index='{{index}}' data-indexx="{{indexx}}">{{itemx.name}}</view>
            </view>
          </view>
        </scroll-view> -->
				<!-- <view v-if="goodsData.goods_reserve == 1">
					<progress class="con-pro" :percent="goodsItem.ratio" show-info />
				</view> -->
				<scroll-view :scroll-y="true" class="attr-list">
					<view class="attr-item-spec">
						<view class="attr-iten-line"></view>
						<view class="attr-item-spec-list">
							<view
								:class="'attr-spec-item ' + (item.selected ? 'active' : '') + ' ' + (item.goods_storage <= 0 ? 'disabled' : '')"
								@tap="onSelectCommon" :data-index="index" v-for="(item, index) in goods_common_list"
								:key="index">
								<view class="attribute-names">{{ item.attribute_names }}</view>

								<view class="goods-unit">￥{{ item.goods_unit_price }}/{{ item.goods_unit }}</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- <view class="goodsInfo" v-if="goodsData.goods_reserve == 1">
			<view class="goods-item-tag">商品会按照预订的时间发货，也可兑换成等价的商品</view>
			<view class="goods-item">
				<view class="lable">供货商家</view>
				<view class="info" @tap="onStore" :data-id="store.id">
					<view class="text">{{ store.store_name }}</view>
					<view class="img">
						<image :src="imgUrl + '/imgs/select-right.png'"></image>
					</view>
				</view>
			</view>
			<view class="goods-item">
				<view class="lable">发票类型</view>
				<view class="info">
					<view class="text">{{ store.invoice }}</view>
					<view class="img"></view>
				</view>
			</view>
			<view class="goods-item">
				<view class="lable">发货时间</view>
				<view class="info">
					<view class="text">{{ goodsData.goods_reserve_send_str }}</view>
					<view class="img"></view>
				</view>
			</view>
		</view> -->
		<view class="goodsInfo" v-if="goodsData.goods_reserve != 1">
			<view class="goods-item">
				<view class="lable">供货商家</view>
				<view class="info" @tap="onStore" :data-id="store.id">
					<view class="text">{{ store.store_name }}</view>
					<view class="img">
						<image :src="imgUrl + '/imgs/select-right.png'"></image>
					</view>
				</view>
			</view>
			<!-- <view class="goods-item">
				<view class="lable">发票类型</view>
				<view class="info">
					<view class="text">{{ store.invoice }}</view>
					<view class="img"></view>
				</view>
			</view>
			<view class="goods-item-text">
				<view class="lable">配送</view>
				<view class="info">
					{{ store.delivery }}
				</view>
			</view> -->
		</view>
		<!-- 详情 -->
		<view class="goodsDetail">
			<view class="goodsDetail-img">
				<view class="goodsDetail-img-list">
					<image :src="item" mode="widthFix" v-for="(item, index) in goodsData.goods_detail" :key="index">
					</image>
				</view>
			</view>
		</view>
		<view class="end"></view>
		<!-- 购买 -->
		<view class="orderSubmit">
			<view class="orderSubmit-view">
				<!-- <view class="orderSubmit-view-item" bindtap="onUpOrCollect" data-type="1" data-oper="{{goodsData.is_collect?'delete':'add'}}">
                <view class="orderSubmit-item-img">
                    <image src="{{imgUrl}}/imgs/goods/collect{{goodsData.is_collect?'-sel':''}}.png"></image>
                </view>
                <view class="orderSubmit-item-text">关注</view>
            </view> -->
				<view class="orderSubmit-view-item">
					<button class="no-button" open-type="contact">
						<view class="orderSubmit-item-img">
							<image :src="imgUrl + '/imgs/goods/serve.png'"></image>
						</view>
						<view class="orderSubmit-item-text">客服</view>
					</button>
				</view>
				<view class="orderSubmit-view-item" @tap="onMyCart" v-if="bean==''">
					<view class="cat-tip" v-if="goodsData.cart_num > 0">
						<view>{{ goodsData.cart_num }}</view>
					</view>
					<view class="orderSubmit-item-img">
						<image :src="imgUrl + '/imgs/goods/cart.png'"></image>
					</view>
					<view class="orderSubmit-item-text">购物车</view>
				</view>
			</view>
			<view class="orderSubmit-but" v-if="(bean=='bean')||(bean=='gift')">
				<view class="orderSubmit-but-cat-right-bean" v-if="goods_number <= 0">
					<view class="orderSubmit-but-but" @tap="setOrder">
						<view class="orderSubmit-but-cat-title">购买</view>
					</view>
				</view>
			</view>
			<view class="orderSubmit-but" v-else>
				<view class="orderSubmit-but-cat-left" v-if="goods_number <= 0">
					<view class="orderSubmit-but-cat-but" @tap="onGoodsAttrOpen">
						<view class="orderSubmit-but-cat-title">购物车</view>
					</view>
				</view>
				<view class="orderSubmit-but-cat-right" v-if="goods_number <= 0">
					<view class="orderSubmit-but-but" @tap="setOrder">
						<view class="orderSubmit-but-cat-title">购买</view>
					</view>
				</view>
				<view class="orderSubmit-but-cat-num" v-if="goods_number > 0">
					<numinput :value="goods_number" type="max" :min="0" :max="goodsItem.goods_storage"
						@change="onNumChange" :index="index" :indexx="indexx"></numinput>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import navber from '@/components/navber/index';
	import msghint from '@/components/msghint/index';
	import numinput from '@/components/numinput/index';

	const Config = require('../../config/index.js');
	const Api = require('../../api/index.js');
	const app = getApp();
	export default {
		components: {
			navber,
			msghint,
			numinput
		},
		data() {
			return {
				navbarData: {
					title: '商品详情',
					//顶部标题
					is_show_bottom: true,
					//显示背景图
					bac_img: '/assets/imgs/navbar/navbar_bg1' //显示背景图片
				},

				//导航栏
				imgUrl: Config.imgUrl,

				//图片url
				goods_id: 0,

				//商品id
				goods_number: 0,
				//商品数量
				bean: '',
				//是否是拼团商品
				goodsData: {
					goods_title: ""
				},

				//数据
				store: [],

				//店铺信息
				is_show: false,

				//是否显示详情
				cartShow: false,

				//显示提示弹窗
				goodsAttrShow: false,

				//显示视频规格选择框
				loginStatus: true,

				//是否登录
				buy_price: 0,

				//
				shareShow: false,

				posterShow: false,
				posterImg: '',
				money: 0,
				attrSku: [],

				//规格组合
				goods_attr_ids: [],

				//
				goods_common_list: [],

				//
				selected_attr_index: [],

				//
				selected_attr_names: '',

				//规格组合显示
				selected_attr_ids: '',

				//选择的id
				clickBtn: 'cat',

				//点击类型
				btnOk: false,

				selectStr: '请选择',

				goodsItem: {
					goods_sell_price: '',
					goods_storage: '',
					bean: 0,
					goods_return_price: 0,
					goods_ratio_price: 0,
					ratio: ''
				},

				//选择好的商品规格
				attrList: [],
				cartList: [],
				business: 1,
				navbarBg: ''
			};
		},
		onLoad: function(option) {
			let goods_id = option.id;
			if (option.scene) {
				//通过海报进入
				let sceneData = decodeURIComponent(option.scene);
				if (sceneData.indexOf('_') > 0) {
					let newData = sceneData.split('_');
					goods_id = newData[0];
					parentId = newData[1];
					app.globalData.top_code = parentId;
					uni.setStorageSync('top_code', parentId);
				}
			}

			if (option.query) {
				//通过分享进入
				if (option.query.code) {
					app.globalData.top_code = option.query.code;
					uni.setStorageSync('top_code', option.query.code);
				}
			}

			let bean = '';
			if (option.bean) {
				bean = option.bean;
			}
			if (goods_id == null || goods_id == undefined || goods_id == '') {
				uni.showToast({
					title: '商品不存在',
					icon: 'error',
					duration: 2000
				});
				setTimeout(function() {
					uni.navigateBack();
				}, 2000);
			} else {
				this.setData({
					goods_id: goods_id,
					bean: bean
				});
				this.getDetail(true);
			}
		},
		onPullDownRefresh: function() {
			this.getDetail();
			uni.stopPullDownRefresh();
		},
		onReachBottom: function() {
			this.setData({
				is_show: true
			}); // 显示加载图标
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			var json = {
				goods_id: this.goodsData.id
			};
			Api.shareAdd(json).then({});
			return {
				title: this.goodsData.goods_title,
				path: '/pages/goodsDetail/index?id=' + this.goodsData.id + '&code=' + app.globalData.popularize_code,
				imageUrl: this.goodsData.goods_img,
				success: function(res) {}
			};
		},
		onShareTimeline: function() {
			var json = {
				goods_id: this.goodsData.id
			};
			Api.shareAdd(json).then({});
			return {
				title: this.goodsData.goods_title,
				path: '/pages/goodsDetail/index?id=' + this.goodsData.id + '&code=' + app.globalData.popularize_code,
				imageUrl: this.goodsData.goods_img,
				success: function(res) {}
			};
		},
		methods: {
			onNumChange(e) {
				let detail = e.detail;
				let goods_number = detail.value;
				this.addCart(goods_number);
			},

			onSelectCommon(e) {
				let index = e.currentTarget.dataset.index;
				let goods_common_list = this.goods_common_list;

				if (goods_common_list[parseInt(index)].goods_storage <= 0) {
					return;
				}

				goods_common_list.forEach((element) => {
					element.selected = false;
				});
				goods_common_list[parseInt(index)].selected = true;
				let selected_attr_ids = goods_common_list[parseInt(index)].attribute_ids;
				this.setData({
					selected_attr_ids: selected_attr_ids,
					goods_common_list: goods_common_list,
					goodsItem: goods_common_list[parseInt(index)],
					selectStr: '已选择'
				});

				if (this.cartList[this.selected_attr_ids] != undefined) {
					let number = parseInt(this.cartList[this.selected_attr_ids]);
					this.setData({
						goods_number: number
					});
				} else {
					this.setData({
						goods_number: 0
					});
				}
			},

			// onSelectAttr(e) {
			//   let index = e.currentTarget.dataset.index;
			//   let indexx = e.currentTarget.dataset.indexx;
			//   let attr_list = this.data.attrList;
			//   if (attr_list[parseInt(index)].list[parseInt(indexx)].disabled) {
			//     return;
			//   }
			//   let list = attr_list[parseInt(index)].list;
			//   for (let i = 0; i < list.length; i++) {
			//     if (i != indexx) {
			//       attr_list[parseInt(index)].list[i].selected = false;
			//     }
			//   }
			//   let selected = attr_list[parseInt(index)].list[parseInt(indexx)].selected;
			//   attr_list[parseInt(index)].list[parseInt(indexx)].selected = !selected;
			//   this.setData({
			//     attrList: attr_list
			//   });
			//   this.doIsGoods();
			// },
			onGoodsAttrOpen(e) {
				this.addCart(1);
			},

			onGoodsAttrClose() {
				//关闭商品属性
				this.setData({
					goodsAttrShow: false
				});
			},

			onGoodsAttrConfirm() {
				if (!this.btnOk) {
					return;
				} //商品规格选择确认

				let selet_ids = [];
				let attrList = this.attrList;

				for (let i = 0; i < attrList.length; i++) {
					let list = attrList[i].list;

					for (let j = 0; j < list.length; j++) {
						if (list[j].selected == true) {
							selet_ids.push(parseInt(list[j].id));
						}
					}
				}

				if (selet_ids.length == attrList.length) {
					// this.setData({
					//   selected_attr_ids:selet_ids.join('_')
					// });
					if (this.clickBtn == 'cat') {
						this.addCart(1);
					} else {
						this.setOrder();
					}
				}

				this.setData({
					goodsAttrShow: false
				});
			},

			getDetail(is_do = false) {
				//详情接口
				var json = {
					goods_id: this.goods_id,
					bean: this.bean
				};
				Api.goodsDetail(json).then((res) => {
					if (res.code == 1) {
						let goods = res.data.goods;
						let store = res.data.store;
						let attr_list = res.data.attr_list;
						let cart_list = res.data.cart_list;
						let goods_attr_ids = res.data.goods_attr_ids;
						let goods_common_list = res.data.goods_common_list;

						if (goods.is_group_goods == 1) {
							var price = goods.goods_bazaar_price - goods.sell_price;
						} else {
							var price = goods.goods_original_price - goods.goods_bazaar_price;
						}

						if (goods.goods_return_money != 0 || goods.goods_top_money != 0) {
							this.setData({
								money: 1
							});
						}

						this.setData({
							goodsData: goods,
							store: store,
							attrList: attr_list,
							cartList: cart_list,
							goods_attr_ids: goods_attr_ids,
							goods_common_list: goods_common_list,
							buy_price: price.toFixed(2)
						});

						if (goods.popularize_code != '') {
							app.globalData.popularize_code = goods.popularize_code;
						}

						if (is_do) {
							this.doIsGoodsCommon();
						}
					} else {
						uni.showToast({
							title: '商品不存在',
							icon: 'error',
							duration: 2000
						});
						setTimeout(function() {
							uni.navigateBack();
						}, 2000);
					} // wx.stopPullDownRefresh();
				});
			},

			onStore(e) {
				let id = e.currentTarget.dataset.id; // wx.navigateTo({
				//   url: '/pages/store/index?id=' + id
				// })
			},

			onToCall() {
				//拨打电话
				// wx.makePhoneCall({
				//   phoneNumber: this.data.store.contact_phone,
				//   success: function () {
				//     console.log('成功拨打电话')
				//   }
				// })
				uni.makePhoneCall({
					phoneNumber: '',
					success: function() {
						console.log('成功拨打电话');
					}
				});
			},

			onUpOrCollect(e) {
				//点赞收藏
				var json = {
					goods_id: this.goodsData.id,
					type: e.currentTarget.dataset.type,
					//类型 1收藏 2点赞
					operation: e.currentTarget.dataset.oper //类型 1收藏 2点赞
				};
				Api.upOrCollect(json).then((res) => {
					if (res.code == 1) {
						this.getDetail();
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						});
					}
				});
			},

			onMyCart() {
				uni.switchTab({
					url: '/pages/cart/index'
				});
			},

			addCart(goods_number) {
				//加入购物车
				var json = {
					goods_id: this.goodsData.id,
					goods_number: goods_number,
					attribute_ids: this.selected_attr_ids
				};
				var self = this;
				Api.goodsAddCart(json).then((res) => {
					if (res.code == 1) {
						this.setData({
							goods_number: goods_number
						});
						self.getMyCartData();
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						});
					}
				});
			},

			getMyCartData() {
				//刷新购物车数量
				let josn = {
					goods_id: this.goodsData.id
				};
				Api.goodsMyCart(josn).then((res) => {
					var data = res.data;
					var cat_sum = data.cat_sum;
					var cart_goods_list = data.cart_goods_list;
					this.setData({
						cartList: cart_goods_list,
						'goodsData.cart_num': cat_sum
					});
				});
			},

			doIsGoodsCommon() {
				let index = -1;
				let that = this;
				let goods_common_list = this.goods_common_list;
				goods_common_list.forEach((element, indexx) => {
					if (element.selected == true) {
						index = indexx;
						that.setData({
							goodsItem: element,
							selectStr: '已选择'
						});
					}
				});
				let selected_attr_ids = goods_common_list[parseInt(index)].attribute_ids;
				this.setData({
					selected_attr_ids: selected_attr_ids
				});

				if (this.cartList[this.selected_attr_ids] != undefined) {
					let number = parseInt(this.cartList[this.selected_attr_ids]);
					this.setData({
						goods_number: number
					});
				} else {
					this.setData({
						goods_number: 0
					});
				}
			},

			doExchangeSku(arr) {
				//获取商品sku关系
				var len = arr.length; // 当数组大于等于2个的时候

				if (len >= 2) {
					// 第一个数组的长度
					var len1 = arr[0].length; // 第二个数组的长度

					var len2 = arr[1].length; // 2个数组产生的组合数

					var lenBoth = len1 * len2; //  申明一个新数组,做数据暂存

					var items = new Array(lenBoth); // 申明新数组的索引

					var index = 0;
					var i = 0;
					var j = 0; // 2层嵌套循环,将组合放到新数组中

					for (i = 0; i < len1; i++) {
						for (j = 0; j < len2; j++) {
							items[index] = arr[0][i] + '_' + arr[1][j];
							index++;
						}
					} // 将新组合的数组并到原数组中

					var newArr = new Array(len - 1);

					for (i = 2; i < arr.length; i++) {
						newArr[i - 1] = arr[i];
					}

					newArr[0] = items; // 执行回调

					return this.doExchangeSku(newArr);
				} else {
					return arr[0];
				}
			},

			setOrder() {
				//设置订单
				var goods_list = [{
					goods_id: this.goodsData.id,
					attribute_ids: this.selected_attr_ids,
					goods_number: 1
				}];
				var goods_list_json = JSON.stringify(goods_list);
				uni.navigateTo({
					url: 'order/index?type=goods_order&goods_info=' + goods_list_json + "&bean=" + this.bean
				});
			}
		}
	};
</script>
<style>
	@import './index.css';
</style>
